'''
Created on Feb 14, 2014

@author: sshadmin
'''
import sys
from xmlrpclib import datetime
sys.path.append("..")
from flask import Flask
from flask import request
import ast
import json
import traceback
import urllib
from flask import render_template
from footy_service import app as footy_servive

from flask import make_response,redirect
import cgi
from datetime import datetime
from pymongo import MongoClient
import gridfs
from model.goalsarena import Main,Match,Youtube,Playwire,User, PageLog,PageSubscriber,Recommended
from bson.objectid import ObjectId
db = MongoClient().pages
from flask import Response
fs = gridfs.GridFS(db)
import logging
import traceback

app = Flask(__name__)
app.register_blueprint(footy_servive)

@app.route('/goalsarena/register' , methods=['GET']) 
@app.route('/register' , methods=['GET'])    
def register():
    try:
        device_id=request.args.get("device_id")
        gcm_key=request.args.get("gcm_key")
        device_name=request.args.get("device_name")
        package_version=request.args.get("package_version")
        email=request.args.get("email")
        android_version=request.args.get("android_version")
        u=User(device_id=device_id,gcm_key=gcm_key,package_version=package_version,email=email,android_version=android_version,device_name=device_name)
        u.save()
        return json.dumps(""),200
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400

  
def page_subscribe():
    try:
        user=request.args.get("user")
        page=request.args.get("page")
        u=PageSubscriber(user=user,page=page,created=datetime.now())
        u.save()
        return json.dumps(""),200
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
    
@app.route('/goalsarena/recommended' , methods=['GET'])         
@app.route('/recommended' , methods=['GET'])   
def recommended():
    try:
        user=request.args.get("user")
        m=Recommended(user)
        matches=m.fetch()
        ret_matches=[]
        for match in matches:
            ret_matches.append(match.to_dic())
        return json.dumps(ret_matches),200
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
     
@app.route('/goalsarena' , methods=['GET'])   
@app.route('/' , methods=['GET'])     
def main():
    try:
        device_id=request.args.get("device_id")
        m=Main()
        matches=m.fetch()
        ret_matches=[]
        for match in matches:
            ret_matches.append(match.to_dic())
        u=PageLog(user=device_id,page="main",created=datetime.now())
        try:
            u.save()
        except:
            pass
        return json.dumps(ret_matches),200
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
@app.route('/goalsarena/match' , methods=['GET']) 
@app.route('/match' , methods=['GET']) 
def match():
    try:
        url=request.args.get("url")
        user=request.args.get("user")
        m=Match(url)
        videos=m.fetch()
        ret_videos=[]
        for video in videos:
            ret_videos.append(video.to_dic())
        u=PageLog(user=user,page=url,created=datetime.now())
        try:
            u.save()
        except:
            logging.info(traceback.format_exc())
        return json.dumps(ret_videos),200
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
@app.route('/video' , methods=['GET']) 
def video():
    try:
        video_type=request.args.get("type")
        video_id=request.args.get("video_id")
        publisher_id=request.args.get("publisher_id")
        if video_type=="youtube":
            print "youtube"
            y=Youtube(video_id)
            return y.load()
        elif video_type=="playwire":
            print "playwire"
            p=Playwire(video_id, publisher_id)
            return p.load()
        else:
            print "error"
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
@app.route('/get_image' , methods=['GET']) 
@app.route('/get_image' , methods=['GET']) 
def get_image():
    try:
        img_id=request.args.get("id")
        photo=fs.get(ObjectId(img_id))
        response = make_response(photo.read())
        response.mimetype = photo.content_type
        return response
    except:
        print traceback.format_exc()
        return json.dumps(traceback.format_exc()), 400
    

    
    
if __name__ == "__main__":
    app.debug = True
    app.run(use_reloader=True, host='0.0.0.0',port=5002)